import requests, json, os
from urllib import parse
from pyaria2 import Aria2RPC
import time
from pyaria2 import Jsonrpc

basePath = 'F:\\code'
typePath = "电台资料"





# 写入：
def WriteFile(fileName, bytes):
    with open(fileName, 'wb') as fileobj:
        fileobj.write(bytes)
# 读取：
def ReadFile(fileName):
    with open(fileName, 'rb', encoding='utf-8') as fileobj:
        for line in fileobj:
            print(line.rstrip())
class GetDianTai:
    def __init__(self):
        self.session = requests.sessions.session()
        self.headers = {}
        self.headers[
            'User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Mobile Safari/537.36'
        self.headers[
            'User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Mobile Safari/537.36'

        self.session.get(url="http://fm.4235d6.com/", headers=self.headers)

    def getzhubo(self):
        path = basePath + "\\" + typePath + "\\音频主播"
        headers = self.headers
        headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
        response = self.session.post(url="http://fm.4235d6.com/plus/user.php", data="act=getNew&atype=0&pageno=1",
                                     headers=headers)
        data = json.loads(response.text)
        dataList = data['list']
        for i in range(len(dataList)):
            print(dataList[i])
            try:
                os.mkdir(path + "\\" + dataList[i]['title'])
            except:
                pass
            writer_url = dataList[i]['writer']
            name = writer_url.split('/')
            name = name[len(name) - 1]
            writer_img = self.session.get(writer_url).content
            WriteFile(fileName=path + "\\" + dataList[i]['title'] + "\\" + name, bytes=writer_img)
            dataList[i]['writer'] = "/" + typePath + "/音频主播" + "/" + dataList[i]['title'] + "/" + name
            dataList[i]['writer'] = parse.quote(dataList[i]['writer'])
            dataList[i]['img'] = dataList[i]['writer']
            response = self.session.post(url="http://fm.4235d6.com/plus/user.php",
                                         data="act=getNewInfo&aid=%s&pageno=1" % (dataList[i]['aid']),
                                         headers=headers)
            data = json.loads(response.text)
            ZhuanJiList = data['list']
            print('专辑列表',ZhuanJiList)
            for ii in range(len(ZhuanJiList)):
                try:
                    os.mkdir(path + "\\" + dataList[i]['title'] + "\\" + ZhuanJiList[ii]['title'])
                except:
                    pass
                yuanxing_img_url = ZhuanJiList[ii]['yuanxing_img']
                name = yuanxing_img_url.split('/')
                name = name[len(name) - 1]
                yuanxing_img = self.session.get(yuanxing_img_url).content
                WriteFile(fileName=path + "\\" + dataList[i]['title'] + "\\" + ZhuanJiList[ii]['title'] + "\\" + name,
                          bytes=yuanxing_img)
                ZhuanJiList[ii]['yuanxing_img'] = "/" + typePath + "/音频主播" + "/" + dataList[i]['title'] + "/" + \
                                                  ZhuanJiList[ii]['title'] + "/" + name
                ZhuanJiList[ii]['yuanxing_img'] = parse.quote(ZhuanJiList[ii]['yuanxing_img'])
                ZhuanJiList[ii]['fangxing_img'] = ZhuanJiList[ii]['fangxing_img']
                response = self.session.post(url="http://fm.4235d6.com/plus/user.php",
                                             data='act=getarticle&aid=%s' % (ZhuanJiList[ii]['id']),
                                             headers=headers)
                data = json.loads(response.text)
                yinpin_file_list = data['yinpin_file']
                print('音频列表', yinpin_file_list)
                for iii in range(len(yinpin_file_list)):
                    _time = yinpin_file_list[iii]['time'].split(":")
                    if len(_time) == 3:
                        yinpin_file_list[iii]['time'] = int(_time[0]) * 60 * 60 + int(_time[1]) * 60 + int(_time[2])
                    if len(_time) == 2:
                        yinpin_file_list[iii]['time'] = int(_time[0]) * 60 + int(_time[1])
                    if len(_time) == 1:
                        yinpin_file_list[iii]['time'] = int(_time[0])
                    yinyue_url = yinpin_file_list[iii]['url']
                    name = yinyue_url.split('/')
                    name = name[len(name) - 1]
                    print("开始下载",yinyue_url)
                    yinyue_data = self.session.get(yinyue_url, headers=headers).content
                    WriteFile(
                        fileName=path + "\\" + dataList[i]['title'] + "\\" + ZhuanJiList[ii]['title'] + "\\" + name,
                        bytes=yinyue_data)
                    yinpin_file_list[iii]['url'] = "/" + typePath + "/音频主播" + "/" + dataList[i]['title'] + "/" + \
                                                   ZhuanJiList[ii]['title'] + "/" + name
                ZhuanJiList[ii]['yinpin_list'] = yinpin_file_list
            dataList[i]['zhuanji_list'] = ZhuanJiList
        WriteFile(fileName=path + "\\dataList.json", bytes=json.dumps(dataList).encode())


def get_file_from_url(link, file_name):
    jsonrpc = Aria2RPC()
    set_dir = os.path.dirname(__file__)
    options = {"dir": set_dir, "out": file_name, }
    res = jsonrpc.addUri([link], options=options)


def get_file_from_cmd(link):
    exe_path = r'D:\aria2\aria2c.exe'
    order = exe_path + ' -s16 -x10 ' + link



if __name__ == "__main__":
    link = 'https://elv1.stride1025.cn/20190530/seo/wydt/Anchor/YQT/Audio/SFBJ/SFBJ003.mp3'
    filename = 'SFBJ003.mp3'

    start = time.time()
    get_file_from_cmd(link)
    end = time.time()
    print(f"耗时:{end - start:.2f}")

    # DT = GetDianTai()
    # DT.getzhubo()
    # print("下载完毕！")
